package com.example.controller;

import com.example.entity.User;
import com.example.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    /**
     * 插入后获取插入的值
     * userService.save方法是开启了事务
     * userService.detail方法挂起了事务(前一个插入没有提交,所以查不到数据),不挂起的话是可以查到刚插入的未提交的数据的
     * String detail()方法体使用了try ... catch(不使用try...catch则事务会回滚,因为设置了"@Transactional(rollbackFor = Exception.class)")
     *
     * @return
     */
    @RequestMapping("/insertAndThenGet")
    @Transactional(rollbackFor = Exception.class)
    public String detail(){
        try {
            User tmp = new User();
            tmp.setId(1);
            tmp.setPassWord("mi吗");
            tmp.setUserName("用户名");
            tmp.setRealName("真实姓名");
            userService.save(tmp);
            return userService.detail(1).toString();
        }catch (Exception ex){
            System.out.println(ex);
        }
        return "出错";
    }
}
